<template>
  <div class="log-container">
    <ButtonGroup
      v-if="showBtn"
      :options="topButton"
      class="button-container"
      @click="handleButtonClick"
    />
    <ContactsSearch v-show="showDetail" ref="ContactForm" @search="getList" />
    <MainTableList
      :columns="columns"
      :data-source="dataSource"
      :row-selection="getRowSelection"
      :loading="loading"
      :scroll="getScroll"
      :pagination="paginationMixin"
      slot-name="name"
      @change="handleTableChange"
      @number-click="handleNumberClick"
    />
    <DialogAddContacts
      :visible.sync="visible"
      :code="code"
      :name="name"
      :form-info="formData"
      :title="title"
      :show-detail="showDetail"
      :show-create="showCreate"
      :is-contacts="isContacts"
      :add-customer="addCustomer"
      @change="handleInsertChange"
      @refresh="getContactsDetailInfo"
    />
  </div>
</template>

<script>
import MainTableList from './mainTableList.vue';
import { getContactsDetail, postContactDelete, postContactsListByPage } from '@/api/customerApi.js';
import mixinTable from '@/mixins/mixin-table.js';
import DialogAddContacts from '@/components/dialog/DialogAddContacts.vue';
import ContactsSearch from './ContactsSearch.vue';

export default {
  components: {
    DialogAddContacts,
    MainTableList,
    ContactsSearch
  },
  mixins: [mixinTable],
  props: {
    code: {
      type: [String, Number],
      default: '',
    },
    name: {
      type: String,
      default: '',
    },
    showBtn: {
      type: Boolean,
      default: false
    },
    rowSelection: {
      type: Object,
      default: () => {},
    },
    showCreate: {
      type: Boolean,
      default: false,
    },
    keyTabs: {
      type: String,
      default: '3',
    },
    showDetail: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      isContacts: false,
      visible: false,
      loading: false,
      formData: {},
      title: '',
      contactStatus: {
        1: '正常',
        2: '冻结'
      },
      genderType: {
        0: '男',
        1: '女'
      },
      addCustomer: true
    };
  },
  computed: {
    getScroll() {
      return this.showBtn ? { x: '100%', y: '53vh' } : { x: '100%', y: 300 }
    },
    getRowSelection() {
      return this.showBtn ? this.rowSelectionMixin : this.rowSelection
    },
    columns() {
      const columns = [
        {
          align: 'center',
          title: '序号',
          width: 60,
          customRender(t, r, index) {
            return parseInt(index) + 1;
          },
        },
        {
          align: 'center',
          title: '姓名',
          dataIndex: 'name',
          ellipsis: true,
          width: 120,
          scopedSlots: { customRender: 'name' },
        },
        {
          align: 'center',
          title: '状态',
          dataIndex: 'contactStatus',
          ellipsis: true,
          customRender: text => this.contactStatus[text],
        },
        {
          align: 'center',
          title: '部门',
          ellipsis: true,
          dataIndex: 'department',
        },
        {
          align: 'center',
          title: '职位',
          ellipsis: true,
          dataIndex: 'position',
        },
        {
          align: 'center',
          title: '职级',
          ellipsis: true,
          dataIndex: 'rankCode',
          customRender: text => this.getRank_code[text],
        },
        {
          align: 'center',
          title: '联系电话',
          dataIndex: 'tel',
          ellipsis: true,
        },
        {
          align: 'center',
          title: '性别',
          dataIndex: 'gender',
          ellipsis: true,
          customRender: text => this.genderType[text],
        },
        {
          align: 'center',
          title: '邮箱',
          dataIndex: 'email',
          ellipsis: true,
        },
        // {
        //   align: 'center',
        //   title: '传真',
        //   dataIndex: 'remark',
        //   ellipsis: true,
        // },
      ];
      return columns;
    },
    topButton() {
      const disabled = !this.rowSelectionMixin.selectedRowKeys.length;
      return [
        {
          key: 'add',
          type: 'primary',
          label: '新增',
          icon: 'plus',
        },
        {
          key: 'delete',
          label: '删除',
          icon: 'delete',
          disabled,
        },
      ];
    },
    getRank_code() {
      return this.$store.state.dictionary.dict['rank_code'] || {};
    }
  },
  watch: {
    keyTabs: {
      handler(newVal) {
        newVal === '3' && this.getList();
      },
      immediate: true,
    }, 
  },
  created() {
    // this.getList();
  },
  methods: {
    handleInsertChange() {
      this.getList();
    },
    getParams() {
      const page = {
        current: this.paginationMixin.current,
        pageSize: this.paginationMixin.pageSize,
        customerCode: this.code,
      };
      return page;
    },
    getList() {
      this.$nextTick(async () => {
        const form = this.$refs.ContactForm.form;
        const data = this.getParams()
        console.log(data)
        this.loading = true;
        const result = await postContactsListByPage({ ...data, ...form }).finally(() => (this.loading = false));
        this.dataSource = result?.data?.data?.records || [];
        this.paginationMixin.total = result?.data?.data?.total || 0;
      });
    },
    handleButtonClick(key) {
      const fn = `${key}Callback`;
      this[fn] && this[fn]();
    },
    addCallback() {
      this.visible = true
      this.title = '新增联系人'
      this.isContacts = false
      this.addCustomer = false
      // this.formData = {}
    },
    async deleteCallback() {
      const selectedRowKeys = this.rowSelectionMixin.selectedRowKeys || [];

      try {
        await this.$confirm(
          `是否删除该联系人？共 ${selectedRowKeys.length} 条，是否确认？`
        );
        let res = await postContactDelete(selectedRowKeys);
        if (res?.data?.data) {
          this.$message.success('删除成功');
          this.rowSelectionMixin.selectedRowKeys = [];
          this.paginationMixin.current = 1
          this.getList();
        } else {
          this.$message.success('删除失败');
        }
      } catch (error) {
        // this.$message.success('删除失败');
        // console.log(error);
      }
    },
    // 编号点击
    async handleNumberClick(record) {
      this.visible = true
      this.title = '编辑联系人'
      this.isContacts = true
      if (this.showDetail) {
        this.title = '联系人详情'
      }
      this.addCustomer = true
      await this.getContactsDetailInfo(record.id)
    },
    async getContactsDetailInfo(id) {
      const res = await getContactsDetail(id)
      this.formData = res?.data?.data || {};
      // console.log(res?.data?.data);
    },
    handleTableChange(page, filters, sorter, { currentDataSource }) {
      this.paginationMixin = page;
      this.getList();
    }
  },
};
</script>

<style lang="less" scoped>
.log-container {
  width: 100%;
}
// .item-container {
//   display: flex;
//   align-items: center;
// }
// .button-container {
//   margin-bottom: 20px;
// }
// .table-container {
//   margin-bottom: 40px;
// }
// /deep/ .poros-select-selection {
//   border: none;
// }
</style>
